package seatiger.tomcat.catalina.session;

import seatiger.tomcat.catalina.Session;

import java.io.*;
import java.util.ArrayList;

/**
 * 文件存储器
 */
public class FileStore extends StoreBase {

    /**
     * session 文件存储的目录 相对路径或者绝对路径
     */
    private String directory = ".";

    /**
     * session 文件存储的目录
     */
    private File directoryFile;

    private static final String FILE_EXT = ".session";

    public void setDirectory(String directory) {
        this.directory = directory;
    }

    @Override
    public Session load(String id) throws ClassNotFoundException, IOException {
        File file = file(id);
        ObjectInputStream ois = null;
        try (FileInputStream fis = new FileInputStream(file.getAbsoluteFile())) {
            BufferedInputStream bis = new BufferedInputStream(fis);
            ois = new ObjectInputStream(bis);
        }
        try {
            StandardSession session = (StandardSession) manager.createEmptySession();
            session.readObjectData(ois);
            session.setManager(manager);
            return session;
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException f) {
                }
            }
        }
    }

    /**
     * 保存session 到存储器中
     *
     * @param session
     * @throws IOException
     */
    @Override
    public void save(Session session) throws IOException {
        File file = file(session.getId());
        try (FileOutputStream fos = new FileOutputStream(file);
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {
            ((StandardSession) session).writeObjectData(oos);
        }
    }

    /**
     * 获取所有的session id
     * @return
     * @throws IOException
     */
    @Override
    public String[] keys() throws IOException {
        File file = directory();
        if (file == null) {
            return (new String[0]);
        }
        String files[] = file.list();
        ArrayList list = new ArrayList();
        int n = FILE_EXT.length();
        for (int i = 0; i < files.length; i++) {
            if (files[i].endsWith(FILE_EXT)) {
                list.add(files[i].substring(0, files[i].length() - n));
            }
        }
        return ((String[]) list.toArray(new String[list.size()]));
    }

    @Override
    public void remove(String id) throws IOException {
        File file = file(id);
        if (file == null) {
            return;
        }
        file.delete();
    }

    /**
     * 获取session存储的文件夹
     *
     * @return
     */
    private File directory() {
        if (directory == null) {
            return null;
        }
        if (directoryFile != null) {
            return directoryFile;
        }
        File file = new File(directory);
        /**
         * 如果不是绝对路径，则使用父容器的work目录
         */
        if (!file.isAbsolute()) {
            //TODO
        }
        if (!file.exists() || !file.isDirectory()) {
            file.delete();
            file.mkdirs();
        }
        this.directoryFile = file;
        return file;
    }

    /**
     * 找到对应的session文件
     *
     * @param id
     * @return
     */
    private File file(String id) {
        String fileName = id + FILE_EXT;
        File file = new File(directory(), fileName);
        return file;
    }

}
